const dbPool = require("../database");

const bcrypt = require("bcryptjs");

const path = require("path");
const express = require("express");
const { resolveSoa } = require("dns");

// 获取个人基本信息回调
exports.getInfo = function (req, res) {
  const sqlStr = "select username, nickname, user_portrait, is_admin from user where id = ?";
  dbPool.query(sqlStr, req.user.id, (err, results) => {
    if (err) return res.cc(err);
    if (results[0]["user_portrait"] === null || results[0]["user_portrait"] === "") {
      results[0]["user_portrait"] = "/assets/user_portrait.jpg";
    }
    if (results[0]["nickname"] === null || results[0]["nickname"] === "") {
      results[0]["nickname"] = results[0]["username"];
    }
    res.send({
      status: 1,
      message: "获取用户基本信息成功",
      data: results[0],
    });
  });
}

// 获取收货地址信息路由回调
exports.getAddressee = function (req, res) {
  const sqlStr = "select name, phone, address from user where id = ?";
  dbPool.query(sqlStr, req.user.id, (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 1,
      message: "获取收获地址成功",
      data: results[0],
    });
  });
}

// 修改用户名
exports.updateNick = function (req, res) {
  const sqlStr = "update user set nickname = ? where id = ?";
  dbPool.query(sqlStr, [req.body.nickname, req.user.id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("用户名修改失败！");
    res.cc("用户名修改成功", 1);
  })
}

// 修改密码路由回调
exports.updatePwd = function (req, res) {
  const sqlStr = "select password from user where id = ?"
  dbPool.query(sqlStr, req.user.id, (err, results) => {
    if (err) return res.cc(err);
    const isMatching = bcrypt.compareSync(req.body.oldPwd, results[0].password);
    if (!isMatching) return res.cc("初始密码不正确");
    req.body.newPwd = bcrypt.hashSync(req.body.newPwd, 10);
    const sqlStr = "update user set password = ? where id = ?";
    dbPool.query(sqlStr, [req.body.newPwd, req.user.id], (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) res.cc("密码修改失败！");
      res.cc("密码修改成功！", 1);
    })
  })
}

// 修改头像
exports.updatePort = function (req, res) {
  if (!req.file || req.file.fieldname !== "user_portrait") return res.cc("头像不能为空！");
  const filePath = "/assets/" + req.file.filename;
  const sqlStr = "update user set user_portrait = ? where id = ?";
  dbPool.query(sqlStr, [filePath, req.user.id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) res.cc("头像修改失败！");
    res.cc("头像修改成功！", 1);
  });
}

exports.updateAddressee = function (req, res) {
  const sqlStr = "update user set ? where id = ?";
  dbPool.query(sqlStr, [req.body, req.user.id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("收获信息修改失败！");
    res.cc("收获信息修改成功！", 1);
  });
}